package com.brush.pig.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.common.constant.CacheConstants;
import com.brush.common.exception.ServiceException;
import com.brush.common.exception.database.PrimaryKeyException;
import com.brush.common.exception.database.RecordNotFoundException;
import com.brush.pig.domain.IotPig;
import com.brush.pig.domain.req.pig.PigAddReq;
import com.brush.pig.domain.req.pig.PigEditReq;
import com.brush.pig.domain.req.pig.PigQueryReq;
import com.brush.pig.domain.req.sow.SowQueryInformationReq;
import com.brush.pig.domain.req.sow.SowUpdateEarCodeReq;
import com.brush.pig.domain.resp.pig.PigResp;
import com.brush.pig.domain.resp.sow.SowQueryInformationResp;
import com.brush.pig.domain.resp.sow.SowQueryTransferResp;
import com.brush.pig.service.IotPigService;
import com.brush.pig.mapper.IotPigMapper;
import com.brush.pig.service.SysDeptFactoryService;
import com.brush.system.mapper.SysDeptMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import com.brush.system.service.SysDeptService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

import java.lang.reflect.Array;
import java.util.List;
import java.util.Objects;

/**
* @author ckq
* @description 针对表【iot_pig(猪只信息)】的数据库操作Service实现
* @createDate 2024-11-12 17:27:27
*/
@Service
public class IotPigServiceImpl extends ServiceImpl<IotPigMapper, IotPig>
    implements IotPigService{

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysDeptFactoryService sysDeptFactoryService;


    /**
     * 母猪信息分页查询
     * @param req
     * @return
     */
    @Override
    public PageInfo<SowQueryInformationResp> getInformation(SowQueryInformationReq req) {
        return PageHelper.startPage(req.getPageNum(),req.getPageSize()).doSelectPageInfo(()->{
           List<SowQueryInformationResp> list = this.baseMapper.getSowInformation(req);
            list.forEach(item -> {
                    Long parentId = getParentIdWithFactoryName(item.getDeptId());
                    if(parentId!=null){
                        String factoryName = sysDeptFactoryService.getAddress(parentId);
                        item.setFactoryName(factoryName);
                    }
            });
        });
    }

    // 私有方法，递归获取其厂区名称的ID
    private Long getParentIdWithFactoryName(Long deptId) {
        String ancestors = sysDeptService.getAncestors(deptId);
        String[] ancestorArray = ancestors.split(",");
        String lastAncestorId =ancestorArray[ancestorArray.length-1];
        String FactoryType=sysDeptService.getType(Long.valueOf(lastAncestorId));
        if(FactoryType.equals("FACTORY")){
            return Long.valueOf(lastAncestorId);
        }else{
            return getParentIdWithFactoryName(Long.valueOf(lastAncestorId));
        }
    }


    @Override
    public boolean updateSowById(SowUpdateEarCodeReq req) {
        IotPig iotPig= this.baseMapper.selectById(req.getId());
        if(Objects.isNull(iotPig)){
            throw new RuntimeException("该猪不存在");
        }
        //判断 earCode 是否重复
        if (!req.getEarCode().equals(iotPig.getEarCode())) {
            if (this.baseMapper.exists(new LambdaQueryWrapper<IotPig>().eq(IotPig::getEarCode, req.getEarCode()))) {
                throw new RuntimeException("耳标已存在");
            }
        }
        return  this.baseMapper.updateEarCodeById(req);
    }

    /**
     * 猪只转场查询
     * @param req
     * @return
     */
    @Override
    public PageInfo<SowQueryTransferResp> getTransfer(SowQueryInformationReq req) {
        return PageHelper.startPage(req.getPageNum(),req.getPageSize()).doSelectPageInfo(()->{
            List<SowQueryTransferResp> list = this.baseMapper.getTransfer(req);
            list.forEach(item -> {
                Long parentId = getParentIdWithFactoryName(item.getDeptId());
                if(parentId==null){
                    String factoryName = sysDeptFactoryService.getAddress(parentId);
                    //来源栏位
                    String sourceName = sysDeptService.getName(item.getDeptId());
                    String targetName = sysDeptService.getName(item.getTargetDeptId());
                    item.setFactoryName(factoryName);
                    item.setDeptName(sourceName);
                    item.setTargetDeptName(targetName);
                }
            });
        });

    }
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageInfo<PigResp> paginationQuery(PigQueryReq req) {
        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            this.baseMapper.paginationQuery(req);
        });
    }

    @Override
    public PigResp findById(Long id) {
        // 验证主键是否存在
        if (Objects.isNull(id)) {
            throw new PrimaryKeyException();
        }
        //根据id查询猪的信息
        IotPig db = this.getById(id);
        //数据库找不到数据
        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }

        //封装成返回对象
        PigResp resp = new PigResp();
        BeanUtils.copyProperties(db, resp);
        return resp;
    }

    @Override
    public boolean add(PigAddReq req) {
        //判断编号是否重复
        if (this.baseMapper.exists(new LambdaQueryWrapper<IotPig>().eq(IotPig::getCode, req.getCode()))) {
            throw new ServiceException("编号重复");
        }
        IotPig db = new IotPig();
        BeanUtils.copyProperties(req, db);

        boolean result = this.save(db);
        if (result) {
            redisTemplate.opsForValue().set(CacheConstants.PIG_KEY + db.getCode(), db);
        }
        return result;
    }

    @Override
    public boolean edit(PigEditReq req) {
        //根据主键id查询
        IotPig db = this.getById(req.getId());
        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }

        //覆盖数据库对象的值
        BeanUtils.copyProperties(req, db);
        boolean result = this.updateById(db);
        if (result) {
            //清除缓存
            redisTemplate.opsForValue().set(CacheConstants.PIG_KEY+db.getCode(), db);
        }
        return result;
    }
}




